﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using RestSharp;
using Newtonsoft.Json.Linq;
using Tradier.Models;
using System.Globalization;

namespace Tradier
{
    public partial class UserOrders : System.Web.UI.Page
    {
        public Dictionary<int, List<OrderModel>> Orders{get;set;}

        protected void Page_Load(object sender, EventArgs e)
        {
            var accessToken = Session["UserTradierAccessToken"];
            if (accessToken == null)
            {
                Response.Redirect("/login.aspx");
            }
            GetUserOrders((string)accessToken);
        }

        private void GetUserOrders(string accessToken)
        {
            try
            {
                var client = new RestClient("https://api.tradier.com");
                var request = new RestRequest("/v1/user/orders", Method.GET);

                request.AddHeader("Authorization", "Bearer " + accessToken);
                var result = (client.Execute(request).Content);
                var json = JObject.Parse(result);

                Orders = CreateMapping(json);
            }
            catch
            {

            }
        }

        private Dictionary<int, List<OrderModel>> CreateMapping(JObject json)
        {
            var orderModel = new Dictionary<int, List<OrderModel>>();
            var accountOrders = new List<OrderModel>();

            var accounts = json["accounts"]["account"];
            if (accounts.GetType().Name == "JArray")
            {
                foreach (JObject account in accounts)
                {
                    accountOrders = new List<OrderModel>();
                    if (account["orders"].HasValues)
                    {

                        var orders = account["orders"]["order"];
                        var accountNumber = (int)account["account_number"];

                        if (orders.GetType().Name == "JArray")
                        {
                            foreach (var order in orders)
                            {
                                var orderItem = new OrderModel()
                                {
                                    Id = (int)order["id"],
                                    Type = (string)order["type"],
                                    Symbol = (string)order["symbol"],
                                    Side = (string)order["side"],
                                    Quantity = (int)order["quantity"],
                                    Status = (string)order["status"],
                                    Duration = (string)order["duration"],
                                    AvgFillPrice = (float)order["avg_fill_price"],
                                    ExecQuantity = (float)order["exec_quantity"],
                                    LastFillPrice = (float)order["last_fill_price"],
                                    LastFillQuantity = (float)order["last_fill_quantity"],
                                    RemainingQuantity = (int)order["remaining_quantity"],
                                    CreateDate = DateTime.ParseExact((string)order["create_date"], "MM/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture),
                                    TransactionDate = DateTime.ParseExact((string)order["transaction_date"], "MM/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture),
                                    Class = (string)order["class"]
                                };

                                if (order["num_legs"] != null)
                                {
                                    orderItem.NumLegs = (int)order["num_legs"];
                                }
                                if (order["option_symbol"] != null)
                                {
                                    orderItem.OptionSymbol = (string)order["option_symbol"];
                                }
                                accountOrders.Add(orderItem);
                            }
                        }
                        else
                        {
                            var order = orders;
                            var orderItem = new OrderModel()
                            {
                                Id = (int)order["id"],
                                Type = (string)order["type"],
                                Symbol = (string)order["symbol"],
                                Side = (string)order["side"],
                                Quantity = (int)order["quantity"],
                                Status = (string)order["status"],
                                Duration = (string)order["duration"],
                                AvgFillPrice = (float)order["avg_fill_price"],
                                ExecQuantity = (float)order["exec_quantity"],
                                LastFillPrice = (float)order["last_fill_price"],
                                LastFillQuantity = (float)order["last_fill_quantity"],
                                RemainingQuantity = (int)order["remaining_quantity"],
                                CreateDate = DateTime.ParseExact((string)order["create_date"], "MM/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture),
                                TransactionDate = DateTime.ParseExact((string)order["transaction_date"], "MM/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture),
                                Class = (string)order["class"]
                            };
                            if (order["num_legs"] != null)
                            {
                                orderItem.NumLegs = (int)order["num_legs"];
                            }
                            if (order["option_symbol"] != null)
                            {
                                orderItem.OptionSymbol = (string)order["option_symbol"];
                            }
                            accountOrders.Add(orderItem);
                        }
                        orderModel.Add(accountNumber, accountOrders);
                    }
                }
            }
            else
            {
                if (accounts["orders"].HasValues)
                {
                    var orders = accounts["orders"]["order"];
                    var accountNumber = (int)accounts["account_number"];
                    accountOrders = new List<OrderModel>();

                    if (orders.GetType().Name == "JArray")
                    {
                        foreach (var order in orders)
                        {
                            var orderItem = new OrderModel()
                            {
                                Id = (int)order["id"],
                                Type = (string)order["type"],
                                Symbol = (string)order["symbol"],
                                Side = (string)order["side"],
                                Quantity = (int)order["quantity"],
                                Status = (string)order["status"],
                                Duration = (string)order["duration"],
                                AvgFillPrice = (float)order["avg_fill_price"],
                                ExecQuantity = (float)order["exec_quantity"],
                                LastFillPrice = (float)order["last_fill_price"],
                                LastFillQuantity = (float)order["last_fill_quantity"],
                                RemainingQuantity = (int)order["remaining_quantity"],
                                CreateDate = DateTime.ParseExact((string)order["create_date"], "MM/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture),
                                TransactionDate = DateTime.ParseExact((string)order["transaction_date"], "MM/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture),
                                Class = (string)order["class"]
                            };
                            if (order["num_legs"] != null)
                            {
                                orderItem.NumLegs = (int)order["num_legs"];
                            }
                            if (order["option_symbol"] != null)
                            {
                                orderItem.OptionSymbol = (string)order["option_symbol"];
                            }
                            accountOrders.Add(orderItem);
                        }
                    }
                    else
                    {
                        var order = orders;
                        var orderItem = new OrderModel()
                        {
                            Id = (int)order["id"],
                            Type = (string)order["type"],
                            Symbol = (string)order["symbol"],
                            Side = (string)order["side"],
                            Quantity = (int)order["quantity"],
                            Status = (string)order["status"],
                            Duration = (string)order["duration"],
                            AvgFillPrice = (float)order["avg_fill_price"],
                            ExecQuantity = (float)order["exec_quantity"],
                            LastFillPrice = (float)order["last_fill_price"],
                            LastFillQuantity = (float)order["last_fill_quantity"],
                            RemainingQuantity = (int)order["remaining_quantity"],
                            CreateDate = DateTime.ParseExact((string)order["create_date"], "MM/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture),
                            TransactionDate = DateTime.ParseExact((string)order["transaction_date"], "MM/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture),
                            Class = (string)order["class"]
                        };
                        if (order["num_legs"] != null)
                        {
                            orderItem.NumLegs = (int)order["num_legs"];
                        }
                        if (order["option_symbol"] != null)
                        {
                            orderItem.OptionSymbol = (string)order["option_symbol"];
                        }
                        accountOrders.Add(orderItem);
                    }
                    orderModel.Add(accountNumber, accountOrders);
                }
            }

            return orderModel;
        }
    }
}